const bcrypt = require('bcryptjs');
const UserModel = require('../user.model');

/**
 * User Service V2
 * Enhanced service with improved features and business logic
 */
class UserServiceV2 {
  /**
   * Get all users with pagination, filtering, and sorting
   */
  static async getAllUsers(options = {}) {
    const {
      page = 1,
      limit = 10,
      search,
      role,
      sort = 'created_at',
      order = 'desc'
    } = options;

    const offset = (page - 1) * limit;

    // 使用共享的 Model 进行数据查询
    const result = await UserModel.findAll({ search, role }, { page, limit });

    // V2 增强格式：将 Model 返回的数据转换为 V2 格式
    const formattedUsers = result.data.map(user => ({
      id: user.id,
      username: user.username,
      email: user.email,
      profile: {
        role: user.role,
        status: user.status,
        is_active: user.status === 'active'
      },
      timestamps: {
        created_at: user.created_at,
        updated_at: user.updated_at
      }
    }));

    return {
      data: formattedUsers,
      pagination: {
        current_page: page,
        total_pages: Math.ceil(result.pagination.total / limit),
        total_items: result.pagination.total,
        items_per_page: limit,
        has_next_page: page < Math.ceil(result.pagination.total / limit),
        has_prev_page: page > 1
      }
    };
  }

  /**
   * Get user by ID with detailed profile (V2 format)
   */
  static async getUserById(id) {
    const user = await UserModel.findById(id);
    
    if (!user) return null;
    
    // V2 enhanced format with nested structure
    return {
      id: user.id,
      username: user.username,
      email: user.email,
      profile: {
        role: user.role,
        status: user.status,
        is_active: user.status === 'active',
        last_login: user.last_login,
        email_verified: user.email_verified || false
      },
      timestamps: {
        created_at: user.created_at,
        updated_at: user.updated_at
      },
      metadata: {
        version: '2.0',
        source: 'api_v2'
      }
    };
  }

  /**
   * Create user with enhanced validation and features (V2)
   */
  static async createUser(userData) {
    const { username, email, password, role = 'user' } = userData;
    
    // V2 enhanced password hashing with higher rounds
    const hashedPassword = await bcrypt.hash(password, 12);
    
    const newUser = await UserModel.create({
      username,
      email,
      password_hash: hashedPassword, // 修复：使用正确的数据库字段名
      role,
      status: 'active',
      email_verified: false
    });
    
    // V2 enhanced format
    return {
      id: newUser.id,
      username: newUser.username,
      email: newUser.email,
      profile: {
        role: newUser.role,
        status: newUser.status,
        is_active: true,
        email_verified: false
      },
      timestamps: {
        created_at: newUser.created_at
      },
      metadata: {
        version: '2.0',
        action: 'created'
      }
    };
  }

  /**
   * Update user (V2 enhanced)
   */
  static async updateUser(id, updateData) {
    const user = await UserModel.findById(id);
    if (!user) return null;

    // Filter allowed update fields
    const allowedFields = ['username', 'email', 'role', 'status'];
    const filteredData = {};
    
    allowedFields.forEach(field => {
      if (updateData[field] !== undefined) {
        filteredData[field] = updateData[field];
      }
    });

    // 使用共享 Model 的 update 方法
    await UserModel.updateById(id, filteredData);

    return this.getUserById(id);
  }

  /**
   * Soft delete user (V2 feature)
   */
  static async deleteUser(id) {
    const user = await UserModel.findById(id);
    if (!user) return null;

    // 使用共享 Model 的软删除方法
    await UserModel.deleteById(id);

    return true;
  }
}

module.exports = UserServiceV2;